const os = require('os');//系统信息
const diskinfo = require('diskinfo');//磁盘信息
const cpuStat = require('cpu-stat');//CPU信息
const format = require('../public/javascripts/format')();
const config = require('../public/javascripts/mongodb.config')
const router = require('koa-router')();

let timeCN = (src)=>{
    let d = Math.floor(src/(3600*24));
    let h = Math.floor(src%(3600*24)/3600);
    let m = Math.floor(src%(3600)/60);
    return (d>0?(`${d}天`):"")+(h>0?(`${h}小时`):"")+`${m}分钟`;
}

let decimals = ((src,n)=>{
    let num = Number(src);
    let pow = Math.pow(10,n);
    return Math.round(num*pow)/pow;
});

let getCPU = (()=>{
    return new Promise((resolve,reject)=>{
        cpuStat.usagePercent((error, percent, seconds) => {
            if(error){
                reject(error);
                return;
            }
            let per = decimals(percent,2);
            resolve({text:`${per}%`,rate:per});
        });
    });
});

let getDisk = (()=>{
    return new Promise((resolve,reject)=>{
        diskinfo.getDrives((error,drivers)=>{
            if(error){
                reject(error);
                return;
            }
            let result = [];
            for(let driver of drivers){
                let total = decimals(driver.blocks/1024/1024/1024,2);
                if(total==0){
                    continue;
                }
                let used = decimals(driver.used/1024/1024/1024,2);
                result.push({
                    name:driver.mounted,
                    text:`${used}/${total} GB`,
                    rate:decimals(decimals((used/total),4)*100,2)
                });   
            }
            resolve(result);
            return;
        });
    });
});

router.get('/hardware', async (ctx) => {
    try {
        let [freemem,totalmem] = [os.freemem(),os.totalmem()];
        let output = {
            hostname:os.hostname(),
            uptime:{text:timeCN(Number(os.uptime()))},
            CPU: {text:"??%"},
            memory: {
                text:(`${parseInt((totalmem-freemem)/ 1024 / 1024)}/${parseInt(totalmem / 1024 / 1024)} MB`),
                rate:decimals(os.freemem()/os.totalmem(),4)*100
            },
            disks:[]
        };
        await getCPU().then(r=>{output.CPU=r}).catch(error=>{throw error});
        await getDisk().then(r=>{output.disks=r}).catch(error=>{throw error});
        ctx.set('Content-Type', 'application/json');
        //ctx.body = query;
        //console.log(JSON.stringify(ctx.request.body));
        return (ctx.response.body = JSON.stringify(output));
    }
    catch (error) {
        return (ctx.response.body = JSON.stringify({ error: error }));
    }
    //return ctx.response.body = {response:'yes'};
});
module.exports = router